/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/


import { ROOT_URL } from '../../config'
import axios from 'axios'
import { parseTime, addSelectField, setDialogContent, setIsDialogOpen, shareData, getPrivilege, setIsLoading, convertArray2String } from '../utils'

// initial state
const state = {
    errors: "",
    options: {},
    my_models: [],
    public_models: [],
    is_dialog_open: false,
    dialog_content: "",
    is_loading: false,
}

// getters
const getters = {
}

// actions
const actions = {
    getUploadOptions({ commit, state }) {
        axios.get(`${ROOT_URL}/api/model/upload_options`, {
        })
            .then((response) => {
                console.log("UploadOptions", response);
                commit('setUploadOptions', response.data)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setUploadOptions', {})
                commit('setErrors', errors)
            })
    },
    getMyModels({ commit, state }) {
        axios.get(`${ROOT_URL}/api/model/models`, {
        })
            .then((response) => {
                const models = response.data;
                for (let m of models) {
                    m.created_time = parseTime(m.created_time)
                    m.is_public = m.is_public? "是": "否"
                    m.task = m.task.reduce(convertArray2String)
                }
                models.map(addSelectField);
                console.log('get my models')
                commit('setMyModels', models)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setMyModels', [])
                commit('setErrors', errors)
            })
    },
    getPublicModels({ commit, state }) {
        axios.get(`${ROOT_URL}/api/model/public_models`, {
        })
            .then((response) => {
                const models = response.data;
                for (let m of models) {
                    m.created_time = parseTime(m.created_time)
                    m.task = m.task.reduce(convertArray2String)
                }
                models.map(addSelectField);
                console.log('get public models')
                commit('setPublicModels', models)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setPublicModels', [])
                commit('setErrors', errors)
            })
    },
    postModel({ dispatch, commit, state }, { file_info, file }) {
        console.log("post model", file_info, file)
        if (file_info.task == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "任务类型不得为空")
        }
        else if (file_info.model_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "模型名称不得为空")
        }
        else if (file_info.dataset_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "数据集名称不得为空")
        }
        else if (file_info.backbone == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "骨架类型不得为空")
        }
        else if (file == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "模型文件不得为空")
        }
        else {
            commit("setIsLoading", true)
            const formData = new FormData();
            formData.append('file', file);
            formData.append('file_info', JSON.stringify(file_info));
            console.log('formData', formData)
            axios.post(`${ROOT_URL}/api/model/models`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            })
                .then((response) => {
                    console.log("post ok", response)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "上传成功")
                    commit("setIsLoading", false)
                    // dispatch('getMyModels')
                })
                .catch((errors) => {
                    console.log("post error", errors)
                    commit('setErrors', errors)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", `上传失败：${errors.response.data}`)
                    commit("setIsLoading", false)
                })
        }
    },
    updateModel({ dispatch, commit, state }, { file_info, model_id}) {
        console.log("update model", file_info)
        if (file_info.task == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "任务类型不得为空")
        }
        else if (file_info.model_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "模型名称不得为空")
        }
        else if (file_info.dataset_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "数据集名称不得为空")
        }
        else if (file_info.backbone == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "骨架类型不得为空")
        }
        else {
            commit("setIsLoading", true)
            const formData = new FormData();
            file_info['model_id']=model_id
            formData.append('file_info', JSON.stringify(file_info));
            console.log('formData', formData)
            axios.put(`${ROOT_URL}/api/model/models`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            })
                .then((response) => {
                    console.log("update ok", response)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "更新成功")
                    commit("setIsLoading", false)
                    // dispatch('getMyModels')
                })
                .catch((errors) => {
                    console.log("update error", errors)
                    commit('setErrors', errors)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", `更新失败：${errors.response.data}`)
                    commit("setIsLoading", false)
                })
        }
    },
    deleteModels({ dispatch, commit, state }, model_ids) {
        // let model_ids = []
        // state.models.forEach(model => { if (model.selected) { model_ids.push(model.id) } });
        console.log('selected', model_ids)
        axios.delete(`${ROOT_URL}/api/model/models`, {
            params: {
                model_ids: model_ids
            }
        })
            .then((response) => {
                console.log('delete success')
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除成功")
                dispatch('getMyModels')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit('setErrors', errors)
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除失败")
                dispatch('getMyModels')
            })
    },
    shareData, getPrivilege
}

const mutations = {
    setErrors(state, errors) {
        state.errors = errors
    },
    setUploadOptions(state, options) {
        state.options = options
    },
    setMyModels(state, models) {
        state.my_models = models
    },
    setPublicModels(state, models) {
        state.public_models = models
    },
    select(state, item) {
        item.selected = !item.selected
    },
    unselectAll(state) {
        state.models.forEach(model => model.selected = false)
    },
    setIsLoading,
    setDialogContent, setIsDialogOpen
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}